﻿<template>
  <v-stepper v-model="step" class="elevation-0">
    <v-stepper-header>
      <v-stepper-step :complete="step > 1" step="1">基本信息</v-stepper-step>
      <v-divider/>
      <v-stepper-step :complete="step > 2" step="2">商品描述</v-stepper-step>
      <v-divider/>
      <v-stepper-step :complete="step > 3" step="3">规格参数</v-stepper-step>
      <v-divider/>
      <v-stepper-step  step="4">完成</v-stepper-step>
    </v-stepper-header>
    <v-stepper-items>
      <!--1、基本信息-->
      <v-stepper-content step="1">
        <v-flex class="xs10 mx-auto">

              <div class="block">
                <el-cascader
                        v-model="goods.categories"
                        :options="options"
                        :props="cascaderProps"
                        placeholder="分类"
                        clearable></el-cascader>
                <p style="color: red" v-if="errors.cate">{{errors.cate}}</p>
              </div>

            <v-spacer></v-spacer>
              <!--品牌-->

            <el-select v-model="goods.brandId" clearable filterable  placeholder="请选择">
              <el-option
                      v-for="item in brands"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
              >
              </el-option>

            </el-select>
            <p style="color: red" v-if="errors.brand">{{errors.brand}}</p>
    <!--          <v-autocomplete box
                              single-line
                              :items="brands"
                              item-text="name"
                              item-value="id"
                              label="品牌"
                              v-model="goods.brandId"
                              autocomplete
                              clearable
                              dense chips
                              required
                              :rules="[v => !!v || '商品品牌不能为空']"
              >
                <template slot="selection" slot-scope="data">
                  <v-chip small>{{ data.item.name}}</v-chip>
                </template>
              </v-autocomplete>-->
          <v-form v-model="valid" ref="basic">
            <v-text-field label="商品名称" v-model="goods.name" :counter="200" required :rules="[v => !!v || '商品名称不能为空']" @mouseover="doValid()"></v-text-field>
            <v-textarea label="商品标题" v-model="goods.caption" :rows="4" :counter="200" :rules="[v => !!v || '商品标题不能为空']"/>
          </v-form>
        </v-flex>
      </v-stepper-content>
      <v-stepper-content step="2">
        <v-textarea label="包装清单"  :counter="1000" :rows="3" hide-details/>
        <v-textarea label="售后服务"  v-model="goods.aftersaleservice" :counter="1000" :rows="3" hide-details
                    class="mb-4"/>
        <v-textarea label="商品描述" v-model="goods.measurement" :rows="4" :counter="200"/>
      </v-stepper-content>

      <v-stepper-content step="3">
        <v-card>
          <v-form v-model="valid2" ref="params">
            <v-text-field label="型号" v-model="goods.modelnum" :counter="200" required :rules="[v => !!v || '商品型号不能为空']"/>
            <v-text-field type="number" label="价格" suffix="元（RMB）"  v-model="goods.price"required :rules="[v => !!v || '商品价格不能为空']"/>
            <v-text-field label="功率" suffix="瓦（W）" v-model="goods.power" :counter="200" required :rules="[v => !!v || '商品功率不能为空']"/>
            <v-text-field label="尺寸" suffix="cm" hint="(50)*(50)" v-model="goods.weight"  required :rules="[v => !!v || '商品尺寸不能为空']"/>
            <v-text-field label="适用范围" suffix="平米" hint="100" v-model="goods.applyspace" required :rules="[v => !!v || '商品适用范围不能为空']"/>
          </v-form>
        </v-card>
        <v-divider></v-divider>


      </v-stepper-content>
      <v-stepper-content step="4">
        <v-flex xs3 offset-xs9>
          <v-btn color="info" @click="submit">保存商品信息</v-btn>
        </v-flex>
      </v-stepper-content>
    </v-stepper-items>
  </v-stepper>
</template>

<script>
  export default {
    name: "goods-form",
    inject:["reload"],
    props: {
      oldGoods: {
        type: Object
      },
      options: {
        type: Array
      },
      isEdit: {
        type: Boolean,
        default: false
      },
      step: {
        type: Number,
        default: 1
      }
    },
    data() {
      return {
        valid: false,
        valid2: false,
        errors:{
          cate: null,
          brand: null
        },
        cascaderProps: {
          //可以选中一级内容
          checkStrictly: true,
          //指定触发方式
          expandTrigger: 'hover',
          //数据源的id做数据绑定
          value: 'id',
          //数据源name渲染出来的内容
          label: 'name',
          //数据源的children做嵌套
          children: 'children'
        },
        categoryList: [],
        goods: {
          categories: [], // 商品分类信息
          brandId: null, // 品牌id信息
          name: "", // 标题
          title: "", // 子标题
        },
        brands: null, // 品牌列表
        specs: [], // 规格参数的模板
        specialSpecs: [], // 特有规格参数模板
      };
    },
    mounted() {
      this.loadOptions()
    },
    methods: {
      loadOptions() {
        this.$http.get("/category/getByCase").then(res => {
          if (res.data.code === 200) {
            this.options = res.data.data
          }else {
            console.log("加载分类列表失败")
          }
        });
        this.$http.get("/brand/list").then(res => {
          if (res.data.code === 200) {
            this.brands = res.data.data
          }else {
            console.log("加载品牌列表失败")
          }
        });
      },
      doValid() {
        if(this.goods.categories===null||this.goods.categories.length===0){
          this.errors.cate="请选择分类"
        }else {
          this.errors.cate=null
        }

        if(this.goods.brandId===null||this.goods.brandId===0){
          this.errors.brand="请选择品牌"
        }else {
          this.errors.brand=null
        }
      },
      submit() {
          this.handleAdd();
      },
      handleAdd() {
        // 表单校验。
        if (!this.$refs.basic.validate||!this.$refs.params.validate) {
          this.$message.error("请先完成表单内容！");
        }
/*        const formData = {
          id:this.goods.id,
          categories:this.goods.categories,
          brandid:this.goods.brandId,
          name:this.goods.name,
          price:this.goods.price,
          modelnum:this.goods.modelnum,
          power:this.goods.power,
          applyspace:this.goods.applyspace,
          measurement:this.goods.measurement,
          weight:this.goods.weight,
          aftersaleservice:this.goods.aftersaleservice,
          caption:this.goods.caption
        } */
        const formData = {
          id:this.goods.id,
          categories:this.goods.categories,
          brandid:this.goods.brandId,
          name:this.goods.name,
          price:this.goods.price,
          modelnum:this.goods.modelnum,
          power:'1200',
          applyspace:'150',
          measurement:"测试数据。。。",
          weight:'50*50',
          aftersaleservice:'三年保修',
          caption:'热辐射电动'
        }
        this.$http({
            method: this.isEdit ? "put" : "post",
            url: "/product/add",
            data: formData
          })
          .then(() => {
            // 成功，关闭窗口
            this.$emit("close");
            // 提示成功
            this.$message.success("保存成功了");
            this.reset();
            this.reload();
          })
          .catch(() => {
            this.$message.error("保存失败！");
          });
      },
      reset(){
        this.goods = {
          categories: [], // 商品分类信息
          brandId: 0, // 品牌id信息
          name: "", // 标题
          title: "", // 子标题
        }
      },
      handleEdit() {
        // 1.判断spu是否修改
        // 1.1.获取spu
        let {id, categories, brandId, name, title} = this.goods;
        let spu = {id, brandId, name, title, cid1: categories[0].id, cid2: categories[1].id, cid3: categories[2].id};
        let spuTitle = title;
        // 1.2.判断spu是否有修改
        const isSpuChange = !Object.compareObj(spu, this.oldGoods);
        if (!isSpuChange) {
          spu = {};
        }
        // 2.判断spuDetail是否修改

        let {...detail} = this.goods.spuDetail;
        const specs = {};
        this.specs.forEach(({id, v}) => {
          specs[id] = v;
        });
        this.specialSpecs.forEach(({id, options}) => {
          specs[id] = options;
        });
        detail.specification = JSON.stringify(specs);
        // 2.3.判断spuDetail是否有修改
        let isDetailChange = false;
        for (let k in detail) {
          if(detail[k] !== this.oldGoods.spuDetail[k]){
            isDetailChange = true;
          }else{
            delete detail[k];
          }
        }
        if (isDetailChange) {
          detail.spuId = this.goods.id;

          spu.spuDetail = detail;
        }
        // 3.判断sku是否修改
        // 3.1.处理sku
        const skus = this.skus
          .map(({title, price, stock, enable, images, indexes, id, ...rest}) => {
            if(!enable){
              return {id, enable:false}
            }
            const obj = {};
            Object.values(rest).forEach(v => {
              obj[v.id] = v.v;
            });
            return {
              id,
              title: title || spuTitle + " " + Object.values(obj).join(" "),
              price: this.$format(price), // 价格需要格式化
              stock,
              indexes,
              images: images ? images.join(",") : '', // 图片
              specialSpec: JSON.stringify(obj) // 特有规格参数
            };
          });
        // 3.3.判断sku是否修改
        let isSkuChange = false;
        for (let i = 0; i < skus.length; i++) {
          let s = skus[i];
          let os = this.oldGoods.skus.find(v => v.id === s.id);
          if (!Object.compareObj(s, os)) {
            isSkuChange = true;
            if(!os && s.enable === false){
              skus.splice(i, 1);
              i--;
            }else if(os && s.enable === false){
              s.saleable = false;
            }
          }else{
            skus.splice(i, 1);
            i--;
          }
          s.spuId = id;
        }
        if (isSkuChange) {
          spu.skus = skus;
        }
        if (isSpuChange || isSkuChange || isDetailChange) {
          // 4.发起请求
          this.$http.put("/item/goods/spu", spu)
            .then(() => {
              // 成功，关闭窗口
              this.$emit("close");
              // 提示成功
              this.$message.success("保存成功了");
            })
            .catch(() => {
              this.$message.error("保存失败！");
            });
        } else {
          // 成功，关闭窗口
          this.$emit("close");
          // 提示成功
          this.$message.warning("商品没有修改！");
        }
      }
    },
    watch: {
      oldGoods: {
        deep: true,
        handler(val) {
          if (!this.isEdit) {
            Object.assign(this.goods, {
              categories: null, // 商品分类信息
              brandId: null, // 品牌id信息
              name: "", // 标题
              title: "", // 子标题
              spuDetail: {
                packingList: "", // 包装列表
                afterService: "", // 售后服务
                description: "" // 商品描述
              }
            });
            this.specs = [];
            this.specialSpecs = [];
          } else {
            this.goods = Object.deepCopy(val);

            // 先得到分类名称
            // const names = val.categoryName.split("/");
            this.goods.categories = [];
            delete this.goods.brand;
            delete this.goods.modifydate;
            delete this.goods.isactive;
            console.log(val)
            // 组织商品分类数据
            var categorys = []
            val.categories.forEach(category=>{
              categorys.push((category.id).toString())
            })
            this.$forceUpdate();
            this.$set(this.goods,'categories',categorys)
            this.categoryList = categorys
            console.log(this.goods)

           /* // 将skus处理成map
            const skuMap = new Map();
            this.goods.skus.forEach(s => {
              s.enable = true;
              skuMap.set(s.indexes, s);
            });
            this.goods.skus = skuMap;*/
          }
        }
      },
      goods: {
        deep: true,
        handler() {
          if (this.isEdit) {
            this.modified = true;
          }
        }
      }
    }
  };
</script>

<style scoped>
</style>
